package com.audaque.springboot.foshanupload.mp.interceptor;

import com.audaque.springboot.foshanupload.mp.handler.iface.TableNameByFieldNameHandler;
import com.baomidou.mybatisplus.core.plugins.InterceptorIgnoreHelper;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.core.toolkit.TableNameParser;

import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Value;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author zgb
 * @desc ...
 * @date 2023-03-04 22:23:51
 */


public class DynamicTableNameByFieldNameInterceptor implements InnerInterceptor {
    private Runnable hook;
    private TableNameByFieldNameHandler tableNameByFieldNameHandler;


    public void setHook(Runnable hook) {
        this.hook = hook;
    }

    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        if (!InterceptorIgnoreHelper.willIgnoreDynamicTableName(ms.getId())) {
            PluginUtils.MPBoundSql mpBs = PluginUtils.mpBoundSql(boundSql);
            mpBs.sql(this.changeTable(mpBs));
        }
    }

    public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) {
        PluginUtils.MPStatementHandler mpSh = PluginUtils.mpStatementHandler(sh);
        MappedStatement ms = mpSh.mappedStatement();
        SqlCommandType sct = ms.getSqlCommandType();
        if (sct == SqlCommandType.INSERT || sct == SqlCommandType.UPDATE || sct == SqlCommandType.DELETE) {
            if (InterceptorIgnoreHelper.willIgnoreDynamicTableName(ms.getId())) {
                return;
            }

            PluginUtils.MPBoundSql mpBs = mpSh.mPBoundSql();
            mpBs.sql(this.changeTable(mpBs));
        }

    }

    protected String changeTable(PluginUtils.MPBoundSql mpBst) {
        String sql = mpBst.sql();
        Map<String, Object> stringObjectMap = mpBst.additionalParameters();
        Object parameterObject = mpBst.parameterObject();

        ExceptionUtils.throwMpe(null == this.tableNameByFieldNameHandler, "Please implement TableNameByFieldNameHandler processing logic", new Object[0]);
        TableNameParser parser = new TableNameParser(sql);
        List<TableNameParser.SqlToken> names = new ArrayList();
        parser.accept(names::add);
        StringBuilder builder = new StringBuilder();
        int last = 0;

        TableNameParser.SqlToken name;
        for (Iterator var6 = names.iterator(); var6.hasNext(); last = name.getEnd()) {
            name = (TableNameParser.SqlToken) var6.next();
            int start = name.getStart();
            if (start != last) {
                builder.append(sql, last, start);
                builder.append(this.tableNameByFieldNameHandler.dynamicTableName(sql, name.getValue(),stringObjectMap));
            }
        }

        if (last != sql.length()) {
            builder.append(sql.substring(last));
        }

        if (this.hook != null) {
            this.hook.run();
        }

        return builder.toString();
    }

    public Runnable getHook() {
        return this.hook;
    }

    public TableNameByFieldNameHandler getTableNameByFieldNameHandler() {
        return this.tableNameByFieldNameHandler;
    }

    public void setTableNameByFieldNameHandler(final TableNameByFieldNameHandler tableNameByFieldNameHandler) {
        this.tableNameByFieldNameHandler = tableNameByFieldNameHandler;
    }

    public DynamicTableNameByFieldNameInterceptor() {
    }

    public DynamicTableNameByFieldNameInterceptor(final Runnable hook, final TableNameByFieldNameHandler tableNameByFieldNameHandler) {
        this.hook = hook;
        this.tableNameByFieldNameHandler = tableNameByFieldNameHandler;
    }
}
